package net.ecpt.hrm.services;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ofbiz.autoconfig.auto.EntitySQLProcessor;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntity;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.wvtools.utils.WvDatetimeUtils;

import javolution.util.FastMap;

/**
 * 
 * 审批功能思路 1. 前台人员操作页面生成草稿状态的数据 2. 传需要审批数据的id 3. service 把业务数据封装成需要提交审批的表单数据 4.
 * 提交审批，获取审批编号，保存入业务表
 */
public class HrmServices {

    public static String module = HrmServices.class.getName();

    /**
     * HR仪表盘数据
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map<String, Object> getHrmDashBoardData(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	try {

	    Map<String, Object> workMap = FastMap.newInstance();

	    // 入职离职数据
	    Map<String, Object> recordResignMap = FastMap.newInstance();
	    // 入职人员列表
	    List<GenericValue> hrEmployeeRecordInfo = delegator.findByAnd("HrEmployeeRecord",
		    UtilMisc.toMap("typeId", "EntryRecord"), UtilMisc.toList("-beginDate"), false);
	    //entryType
	    if (hrEmployeeRecordInfo.size() > 4) {
		hrEmployeeRecordInfo = hrEmployeeRecordInfo.subList(0, 4);
	    }

	    List hrEmployeeRecordList = new ArrayList();
	    for (GenericValue gv : hrEmployeeRecordInfo) {
		Map map = new HashMap();
		String departmentId = gv.getString("departmentId");
		map.putAll(gv);

		List<GenericValue> hrDepartmentInfo = delegator.findByAnd("HrDepartment",
			UtilMisc.toMap("departmentId", departmentId), UtilMisc.toList("id"), true);
		GenericValue hrDepartment = EntityUtil.getFirst(hrDepartmentInfo);
		if (UtilValidate.isNotEmpty(hrDepartment)) {
		    String departmentId_dictText = hrDepartment.getString("name");
		    map.put("departmentId_dictText", departmentId_dictText);
		}
		hrEmployeeRecordList.add(map);

	    }

	    
	    List<GenericValue> hrResignInfo = delegator.findByAnd("Person", UtilMisc.toMap("workState", "2"),
			    UtilMisc.toList("-notWorkDate"), true);
		    List hrResignList = new ArrayList();
		    if (hrResignInfo.size() > 4) {
			hrResignInfo = hrResignInfo.subList(0, 4);
		    }
		    for (GenericValue person : hrResignInfo) {
			Map map = new HashMap();
//			String partyId = gv.getString("partyId");
			map.putAll(person);
//			GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", partyId), true);
			if (UtilValidate.isNotEmpty(person)) {
			    String departmentId = person.getString("departmentId");
			    String partyId_dictText = person.getString("name");
			    map.put("partyId_dictText", partyId_dictText);
			    List<GenericValue> hrDepartmentInfo = delegator.findByAnd("HrDepartment",
				    UtilMisc.toMap("departmentId", departmentId), UtilMisc.toList("id"), true);
			    GenericValue hrDepartment = EntityUtil.getFirst(hrDepartmentInfo);
			    if (UtilValidate.isNotEmpty(hrDepartment)) {
				String departmentId_dictText = hrDepartment.getString("name");
				map.put("departmentId_dictText", departmentId_dictText);
			    }
			    map.putAll(person);
			}

			hrResignList.add(map);

		    }

	    recordResignMap.put("hrEmployeeRecordList", hrEmployeeRecordList);
	    recordResignMap.put("hrResignList", hrResignList);
	    workMap.put("recordResignMap", recordResignMap);

	    // 全部职员列表
	    // List<GenericValue> personList = delegator.findByAnd("Person",
	    // UtilMisc.toMap("typeId","EMPLOYEE"),UtilMisc.toList("-createDate"), true);

	    // 员工工作年限分析
	    String beginDateYearNumSql = "select '0-1' 工龄, count(*) 人数 from person where work_State !=2 and  begin_date_year_num between 0 and 1 union all select '1-3' 年龄段, count(*) 人数 from person  where work_State !=2 and  begin_date_year_num  between 1 and 3 union all select '3-5' 年龄段, count(*) 人数 from person  where work_State !=2 and  begin_date_year_num  between 3 and 5 union all select '5-10' 年龄段, count(*) 人数 from person  where work_State !=2 and  begin_date_year_num  between 5 and 10 union all select '10-' 年龄段, count(*) 人数 from person  where work_State !=2 and  begin_date_year_num  > 10";

	    // 员工性别分析
	    String genderSql = "select b.description 性别,count(p.gender) 人数 from person p, Data_Dictionary b  where p.work_State !=2 and p.gender=b.dictionary_Code and b.dictionary_Type_Id='USER_SEX'  group by b.description";

	    // 按月统计员工入职
	    String ruzhiSql = "select year(p.begin_date),month(p.begin_date),count(p.begin_date) 人数 from person p where p.work_State !=2 and  p.begin_date > '2019-01-01 12:00:00.000' group by year(p.begin_date),month(p.begin_date)";

	    // 按月统计员工离职
	    String lizhiSql = "select year(p.not_work_date),month(p.not_work_date),count(p.not_work_date) 人数 from person p where p.work_State !=2 and  p.not_work_date > '2019-01-01 12:00:00.000' group by year(p.not_work_date),month(p.not_work_date)";

	    // 统计员工年龄段
	    String nianlignduanSql = "select '0-20' 年龄段, count(*) 人数 from person where work_State !=2 and  age between 0 and 20 	union all select '21-30' 年龄段, count(*) 人数 from person  where work_State !=2 and  age  between 21 and 30 	union all select '31-40' 年龄段, count(*) 人数 from person  where work_State !=2 and  age  between 31 and 40 	union all select '41-50' 年龄段, count(*) 人数 from person  where work_State !=2 and  age  between 41 and 50 union all select '51-60' 年龄段, count(*) 人数 from person  where work_State !=2 and  age  > 50";

	    // 统计员工分类
	    String categoryIdSql = "select b.description 分类,count(p.category_id) 人数 from person p, Data_Dictionary b  where p.work_State !=2 and  p.category_id=b.dictionary_Code and b.dictionary_Type_Id='STAFF_SORT'  group by b.description";

	    // 统计员工状态
	    String workStateSql = "select b.description 状态,count(p.work_State) 人数 from person p, Data_Dictionary b  where p.work_State=b.dictionary_Code and b.dictionary_Type_Id='EMP_WORK_STATE'  group by b.description";

	    Map sqlCommand_beginDateYearNumSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", beginDateYearNumSql));
	    Debug.log("sqlCommand_beginDateYearNumSql:" + sqlCommand_beginDateYearNumSql);
	    List beginDateYearNumDataList = (List) sqlCommand_beginDateYearNumSql.get("records");// 记录
	    List beginDateYearNumKeyList = (List) sqlCommand_beginDateYearNumSql.get("columns");// 列名

	    workMap.put("beginDateYearNumDataList", beginDateYearNumDataList);
	    workMap.put("beginDateYearNumKeyList", beginDateYearNumKeyList);

	    Map sqlCommand_genderSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", genderSql));
	    Debug.log("sqlCommand_genderSql:" + sqlCommand_genderSql);
	    List genderDataList = (List) sqlCommand_genderSql.get("records");// 记录
	    List genderKeyList = (List) sqlCommand_genderSql.get("columns");// 列名

	    workMap.put("genderDataList", genderDataList);
	    workMap.put("genderKeyList", genderKeyList);

	    Map sqlCommand_ruzhiSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", ruzhiSql));
	    Debug.log(",sqlCommand1:" + sqlCommand_ruzhiSql);
	    List ruzhiDataList = (List) sqlCommand_ruzhiSql.get("records");// 记录
	    List ruzhiKeyList = (List) sqlCommand_ruzhiSql.get("columns");// 列名

	    workMap.put("ruzhiDataList", ruzhiDataList);
	    workMap.put("ruzhiKeyList", ruzhiKeyList);

	    Map sqlCommand_lizhiSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", lizhiSql));
	    Debug.log(",sqlCommand_lizhiSql:" + sqlCommand_lizhiSql);
	    List lizhiDataList = (List) sqlCommand_lizhiSql.get("records");// 记录
	    List lizhiKeyList = (List) sqlCommand_lizhiSql.get("columns");// 列名

	    workMap.put("lizhiDataList", lizhiDataList);
	    workMap.put("lizhiKeyList", lizhiKeyList);

	    Map sqlCommand_nianlignduanSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", nianlignduanSql));
	    Debug.log(",sqlCommand_nianlignduanSql:" + sqlCommand_nianlignduanSql);
	    List nianlignduanDataList = (List) sqlCommand_nianlignduanSql.get("records");// 记录
	    List nianlignduanKeyList = (List) sqlCommand_nianlignduanSql.get("columns");// 列名

	    workMap.put("nianlignduanDataList", nianlignduanDataList);
	    workMap.put("nianlignduanKeyList", nianlignduanKeyList);

	    Map sqlCommand_categoryIdSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", categoryIdSql));
	    Debug.log(",sqlCommand_categoryIdSql:" + sqlCommand_categoryIdSql);
	    List categoryIdDataList = (List) sqlCommand_categoryIdSql.get("records");// 记录
	    List categoryIdKeyList = (List) sqlCommand_categoryIdSql.get("columns");// 列名

	    workMap.put("categoryIdDataList", categoryIdDataList);
	    workMap.put("categoryIdKeyList", categoryIdKeyList);

	    Map sqlCommand_workStateSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", workStateSql));
	    Debug.log(",sqlCommand_workStateSql:" + sqlCommand_workStateSql);
	    List workStateDataList = (List) sqlCommand_workStateSql.get("records");// 记录
	    List workStateKeyList = (List) sqlCommand_workStateSql.get("columns");// 列名

	    workMap.put("workStateDataList", workStateDataList);
	    workMap.put("workStateKeyList", workStateKeyList);

	    
	    workMap.put("toDoList", hrToDoList(delegator));
	    result.put("workMap", workMap);
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }
    
    
    /**
     * HR仪表盘数据
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map<String, Object> getHrmDashBoardDataBu(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	try {
        GenericValue userLogin=(GenericValue) context.get("userLogin");
       
        String userLogin_partyId =userLogin.getString("partyId");
		 GenericValue userLogin_person = delegator.findOne("Person", UtilMisc.toMap("partyId", userLogin_partyId), false);
		 String userLogin_departmentId = userLogin_person.getString("departmentId");
	    Map<String, Object> workMap = FastMap.newInstance();

	    // 入职离职数据
	    Map<String, Object> recordResignMap = FastMap.newInstance();
	    // 入职人员列表
	    List<GenericValue> hrEmployeeRecordInfo = delegator.findByAnd("HrEmployeeRecord",
		    UtilMisc.toMap("typeId", "EntryRecord","departmentId",userLogin_departmentId), UtilMisc.toList("-beginDate"), true);

	    if (hrEmployeeRecordInfo.size() > 4) {
		hrEmployeeRecordInfo = hrEmployeeRecordInfo.subList(0, 4);
	    }

	    List hrEmployeeRecordList = new ArrayList();
	    for (GenericValue gv : hrEmployeeRecordInfo) {
		Map map = new HashMap();
		String departmentId = gv.getString("departmentId");
		map.putAll(gv);

		List<GenericValue> hrDepartmentInfo = delegator.findByAnd("HrDepartment",
			UtilMisc.toMap("departmentId", departmentId), UtilMisc.toList("id"), true);
		GenericValue hrDepartment = EntityUtil.getFirst(hrDepartmentInfo);
		if (UtilValidate.isNotEmpty(hrDepartment)) {
		    String departmentId_dictText = hrDepartment.getString("name");
		    map.put("departmentId_dictText", departmentId_dictText);
		}
		hrEmployeeRecordList.add(map);

	    }

	    // 离职人员列表
	    List<GenericValue> hrResignInfo = delegator.findByAnd("HrResign", UtilMisc.toMap("statusId", "2","buId",userLogin_departmentId),
		    UtilMisc.toList("-estimateResignDate"), true);
	    List hrResignList = new ArrayList();
	    if (hrResignInfo.size() > 4) {
		hrResignInfo = hrResignInfo.subList(0, 4);
	    }
	    for (GenericValue gv : hrResignInfo) {
		Map map = new HashMap();
		String partyId = gv.getString("partyId");
		map.putAll(gv);
		GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", partyId), true);
		if (UtilValidate.isNotEmpty(person)) {
		    String departmentId = person.getString("departmentId");
		    String partyId_dictText = person.getString("name");
		    map.put("partyId_dictText", partyId_dictText);
		    List<GenericValue> hrDepartmentInfo = delegator.findByAnd("HrDepartment",
			    UtilMisc.toMap("departmentId", departmentId), UtilMisc.toList("id"), true);
		    GenericValue hrDepartment = EntityUtil.getFirst(hrDepartmentInfo);
		    if (UtilValidate.isNotEmpty(hrDepartment)) {
			String departmentId_dictText = hrDepartment.getString("name");
			map.put("departmentId_dictText", departmentId_dictText);
		    }
		    map.putAll(person);
		}

		hrResignList.add(map);

	    }

	    recordResignMap.put("hrEmployeeRecordList", hrEmployeeRecordList);
	    recordResignMap.put("hrResignList", hrResignList);
	    workMap.put("recordResignMap", recordResignMap);

	    // 全部职员列表
	    // List<GenericValue> personList = delegator.findByAnd("Person",
	    // UtilMisc.toMap("typeId","EMPLOYEE"),UtilMisc.toList("-createDate"), true);

	    // 员工工作年限分析
	    String beginDateYearNumSql = "select '0-1' 工龄, count(*) 人数 from person where work_State !=2 and  begin_date_year_num between 0 and 1 union all select '1-3' 年龄段, count(*) 人数 from person  where work_State !=2 and  begin_date_year_num  between 1 and 3 union all select '3-5' 年龄段, count(*) 人数 from person  where work_State !=2 and  begin_date_year_num  between 3 and 5 union all select '5-10' 年龄段, count(*) 人数 from person  where work_State !=2 and  begin_date_year_num  between 5 and 10 union all select '10-' 年龄段, count(*) 人数 from person  where work_State !=2 and  department_Id ="+userLogin_departmentId+" and begin_date_year_num  > 10";

	    // 员工性别分析
	    String genderSql = "select b.description 性别,count(p.gender) 人数 from person p, Data_Dictionary b  where p.work_State !=2 and  department_Id ="+userLogin_departmentId+" and p.gender=b.dictionary_Code and b.dictionary_Type_Id='USER_SEX'  group by b.description";

	    // 按月统计员工入职
	    String ruzhiSql = "select year(p.begin_date),month(p.begin_date),count(p.begin_date) 人数 from person p where p.work_State !=2 and  department_Id ="+userLogin_departmentId+" and p.begin_date > '2019-01-01 12:00:00.000' group by year(p.begin_date),month(p.begin_date)";

	    // 按月统计员工离职
	    String lizhiSql = "select year(p.not_work_date),month(p.not_work_date),count(p.not_work_date) 人数 from person p where p.work_State !=2 and  department_Id ="+userLogin_departmentId+" and p.not_work_date > '2019-01-01 12:00:00.000' group by year(p.not_work_date),month(p.not_work_date)";

	    // 统计员工年龄段
	    String nianlignduanSql = "select '0-20' 年龄段, count(*) 人数 from person where work_State !=2 and  department_Id ="+userLogin_departmentId+" and age between 0 and 20 	union all select '21-30' 年龄段, count(*) 人数 from person  where work_State !=2 and  department_Id ="+userLogin_departmentId+" and age  between 21 and 30 	union all select '31-40' 年龄段, count(*) 人数 from person  where work_State !=2 and  department_Id ="+userLogin_departmentId+" and age  between 31 and 40 	union all select '41-50' 年龄段, count(*) 人数 from person  where work_State !=2 and  department_Id ="+userLogin_departmentId+" and age  between 41 and 50 union all select '51-60' 年龄段, count(*) 人数 from person where work_State !=2 and department_Id ="+userLogin_departmentId+" and  age  > 50";

	    // 统计员工分类
	    String categoryIdSql = "select b.description 分类,count(p.category_id) 人数 from person p, Data_Dictionary b  where p.work_State !=2 and  department_Id ="+userLogin_departmentId+" and p.category_id=b.dictionary_Code and b.dictionary_Type_Id='STAFF_SORT'  group by b.description";

	    // 统计员工状态
	    String workStateSql = "select b.description 状态,count(p.work_State) 人数 from person p, Data_Dictionary b  where p.work_State !=2 and  department_Id ="+userLogin_departmentId+" and p.work_State=b.dictionary_Code and b.dictionary_Type_Id='EMP_WORK_STATE'  group by b.description";

	    Map sqlCommand_beginDateYearNumSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", beginDateYearNumSql));
	    Debug.log("sqlCommand_beginDateYearNumSql:" + sqlCommand_beginDateYearNumSql);
	    List beginDateYearNumDataList = (List) sqlCommand_beginDateYearNumSql.get("records");// 记录
	    List beginDateYearNumKeyList = (List) sqlCommand_beginDateYearNumSql.get("columns");// 列名

	    workMap.put("beginDateYearNumDataList", beginDateYearNumDataList);
	    workMap.put("beginDateYearNumKeyList", beginDateYearNumKeyList);

	    Map sqlCommand_genderSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", genderSql));
	    Debug.log("sqlCommand_genderSql:" + sqlCommand_genderSql);
	    List genderDataList = (List) sqlCommand_genderSql.get("records");// 记录
	    List genderKeyList = (List) sqlCommand_genderSql.get("columns");// 列名

	    workMap.put("genderDataList", genderDataList);
	    workMap.put("genderKeyList", genderKeyList);

	    Map sqlCommand_ruzhiSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", ruzhiSql));
	    Debug.log(",sqlCommand1:" + sqlCommand_ruzhiSql);
	    List ruzhiDataList = (List) sqlCommand_ruzhiSql.get("records");// 记录
	    List ruzhiKeyList = (List) sqlCommand_ruzhiSql.get("columns");// 列名

	    workMap.put("ruzhiDataList", ruzhiDataList);
	    workMap.put("ruzhiKeyList", ruzhiKeyList);

	    Map sqlCommand_lizhiSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", lizhiSql));
	    Debug.log(",sqlCommand_lizhiSql:" + sqlCommand_lizhiSql);
	    List lizhiDataList = (List) sqlCommand_lizhiSql.get("records");// 记录
	    List lizhiKeyList = (List) sqlCommand_lizhiSql.get("columns");// 列名

	    workMap.put("lizhiDataList", lizhiDataList);
	    workMap.put("lizhiKeyList", lizhiKeyList);

	    Map sqlCommand_nianlignduanSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", nianlignduanSql));
	    Debug.log(",sqlCommand_nianlignduanSql:" + sqlCommand_nianlignduanSql);
	    List nianlignduanDataList = (List) sqlCommand_nianlignduanSql.get("records");// 记录
	    List nianlignduanKeyList = (List) sqlCommand_nianlignduanSql.get("columns");// 列名

	    workMap.put("nianlignduanDataList", nianlignduanDataList);
	    workMap.put("nianlignduanKeyList", nianlignduanKeyList);

	    Map sqlCommand_categoryIdSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", categoryIdSql));
	    Debug.log(",sqlCommand_categoryIdSql:" + sqlCommand_categoryIdSql);
	    List categoryIdDataList = (List) sqlCommand_categoryIdSql.get("records");// 记录
	    List categoryIdKeyList = (List) sqlCommand_categoryIdSql.get("columns");// 列名

	    workMap.put("categoryIdDataList", categoryIdDataList);
	    workMap.put("categoryIdKeyList", categoryIdKeyList);

	    Map sqlCommand_workStateSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", workStateSql));
	    Debug.log(",sqlCommand_workStateSql:" + sqlCommand_workStateSql);
	    List workStateDataList = (List) sqlCommand_workStateSql.get("records");// 记录
	    List workStateKeyList = (List) sqlCommand_workStateSql.get("columns");// 列名

	    workMap.put("workStateDataList", workStateDataList);
	    workMap.put("workStateKeyList", workStateKeyList);

	    
	    workMap.put("toDoList", hrToDoList(delegator));
	    result.put("workMap", workMap);
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }
    
    /**
     * hr待办事项
     * 
     * 待入职
     * 待转正
     * 待离职
     * 
     * 合同到期
     * 生日
     * 入职周年
     * @throws GenericEntityException 
     * @throws ParseException 
     */
    private static Map hrToDoList(Delegator delegator) throws GenericEntityException, ParseException {
    	Map result= new HashMap();
    	
    	List todoList1 =new ArrayList();
    	List todoList2 =new ArrayList();
    	List todoList3 =new ArrayList();
    	List todoList4 =new ArrayList();
    	List todoList5 =new ArrayList();
    	List todoList6 =new ArrayList();
    	//本日 ，本周，本月 ，本年
		Date date = new Date();
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date);
		// 将时分秒,毫秒域清零
		cal1.set(Calendar.HOUR_OF_DAY, 0);
		cal1.set(Calendar.MINUTE, 0);
		cal1.set(Calendar.SECOND, 0);
		cal1.add(Calendar.DATE, 1);
		date = cal1.getTime();
		// 查询当日应该是今天到明天为止
		Timestamp thruDate = new Timestamp(date.getTime());
		Debug.log("thruDate=" + thruDate);
		List mainCond0 = new ArrayList();
		Timestamp fromDate = WvDatetimeUtils.getLastDay(thruDate, new Long(-31));
		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond0.add(EntityCondition.makeCondition("createTime", EntityOperator.LESS_THAN, thruDate));

		
		
    	List mainCond1 = new ArrayList();
		mainCond1.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EntryRecord"));
		mainCond1.add(EntityCondition.makeCondition("entryType", EntityOperator.EQUALS,  GenericEntity.NULL_FIELD));
		Long todoNum1 = delegator.findCountByCondition("HrEmployeeRecord",
			EntityCondition.makeCondition(mainCond1, EntityOperator.AND), null, null);
		Debug.log("todoNum1 = "+todoNum1);
		todoList1 = delegator.findList("HrEmployeeRecord", EntityCondition.makeCondition(mainCond1, EntityOperator.AND), null, UtilMisc.toList("beginDate"), null, false);
		
		List mainCond2 = new ArrayList();
		mainCond2.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
		mainCond2.add(EntityCondition.makeCondition("workState", EntityOperator.EQUALS, "0"));
		mainCond0.add(EntityCondition.makeCondition("conversionTime", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond0.add(EntityCondition.makeCondition("conversionTime", EntityOperator.LESS_THAN, thruDate));

		
		
		Long todoNum2 = delegator.findCountByCondition("Person",
			EntityCondition.makeCondition(mainCond2, EntityOperator.AND), null, null);
		 todoList2 = delegator.findList("Person", EntityCondition.makeCondition(mainCond2, EntityOperator.AND), null, UtilMisc.toList("conversionTime"), null, false);
		 //
		List mainCond3 = new ArrayList();
		mainCond3.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "1"));
		Long todoNum3 = delegator.findCountByCondition("HrResign",
			EntityCondition.makeCondition(mainCond3, EntityOperator.AND), null, null);
		List<GenericValue> hrResignList = delegator.findList("HrResign", EntityCondition.makeCondition(mainCond3, EntityOperator.AND), null, UtilMisc.toList("estimateResignDate"), null, false);
//		
		todoList3 =hrResignList;
		
		 
		
		
		List mainCond4 = new ArrayList();
		mainCond4.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
		mainCond4.add(EntityCondition.makeCondition("workState", EntityOperator.EQUALS, "1"));
		mainCond4.add(EntityCondition.makeCondition("endContract", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
		mainCond4.add(EntityCondition.makeCondition("endContract", EntityOperator.LESS_THAN, thruDate));

		Long todoNum4 = delegator.findCountByCondition("Person",
			EntityCondition.makeCondition(mainCond4, EntityOperator.AND), null, null);
		 todoList4 = delegator.findList("Person", EntityCondition.makeCondition(mainCond4, EntityOperator.AND), null, UtilMisc.toList("-createdStamp"), null, false);
//			
//		List mainCond5 = new ArrayList();
//		mainCond5.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
//		mainCond5.add(EntityCondition.makeCondition("birthday", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate));
//		mainCond5.add(EntityCondition.makeCondition("birthday", EntityOperator.LESS_THAN, thruDate));
//
//		Long todoNum5 = delegator.findCountByCondition("Person",
//			EntityCondition.makeCondition(mainCond5, EntityOperator.AND), null, null);
		Long todoNum5 = 0L;
		List<GenericValue> personList = delegator.findByAnd("Person",UtilMisc.toMap("typeId", "EMPLOYEE"), UtilMisc.toList("birthday"), true);
		for(GenericValue person : personList) {
			Timestamp birthday =person.getTimestamp("birthday");
			if(UtilValidate.isNotEmpty(birthday)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
				String time = sdf.format(birthday);
				Debug.log(person.getString("name")+"=="+time);
				long days =getBirthDayNumber(time);
				if(days < 31) {	
					todoNum5 = todoNum5+1; 
					todoList5.add(person);
				}
			}
		}
		
		Timestamp fromDateYear = WvDatetimeUtils.getLastDay(thruDate, new Long(-365));
		Timestamp thruDateYear = WvDatetimeUtils.getLastDay(thruDate, new Long(-334));
		
		
		List mainCond6 = new ArrayList();
		mainCond6.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
		mainCond6.add(EntityCondition.makeCondition("beginDate", EntityOperator.GREATER_THAN_EQUAL_TO, fromDateYear));
		mainCond6.add(EntityCondition.makeCondition("beginDate", EntityOperator.LESS_THAN, thruDateYear));

		Long todoNum6 = delegator.findCountByCondition("Person",
			EntityCondition.makeCondition(mainCond6, EntityOperator.AND), null, null);
		
		 todoList6 = delegator.findList("Person", EntityCondition.makeCondition(mainCond6, EntityOperator.AND), null, UtilMisc.toList("beginDate"), null, false);
//		 Long todoNum6 =todoList6.size();

		result.put("todoNum1", todoNum1);
		result.put("todoNum2", todoNum2);
		result.put("todoNum3", todoNum3);
		result.put("todoNum4", todoNum4);
		result.put("todoNum5", todoNum5);
		result.put("todoNum6", todoNum6);
		result.put("todoList1", buildDepartmentList(delegator,todoList1));
		result.put("todoList2", buildDepartmentList(delegator,todoList2));
		result.put("todoList3", buildPersonList(delegator,todoList3));
		result.put("todoList4", buildDepartmentList(delegator,todoList4));
		result.put("todoList5", buildDepartmentList(delegator,todoList5));
		result.put("todoList6", buildDepartmentList(delegator,todoList6));
    	return result;
    	
//    	
//    	* 待入职      beginDate
//        * 待转正  conversionTime
//        * 待离职  estimateResignDate期望离职日期
//        * 
//        * 合同到期  endContract
//        * 生日          birthday  显示时候去掉年份
//        * 入职周年
    }
    
    private static List buildDepartmentList(Delegator delegator,List<GenericValue> inList) {
    	List result=new ArrayList();
    	try {
    	for(GenericValue person:inList) {
    		Map map =new HashMap();
    	
		    String departmentId = person.getString("departmentId");
		    String partyId_dictText = person.getString("name");
		    map.put("partyId_dictText", partyId_dictText);
		    List<GenericValue> hrDepartmentInfo = delegator.findByAnd("HrDepartment",
			    UtilMisc.toMap("departmentId", departmentId), UtilMisc.toList("id"), true);
		    GenericValue hrDepartment = EntityUtil.getFirst(hrDepartmentInfo);
		    if (UtilValidate.isNotEmpty(hrDepartment)) {
			String departmentId_dictText = hrDepartment.getString("name");
			map.put("departmentId_dictText", departmentId_dictText);
			String parentId = hrDepartment.getString("parentId");
				if (UtilValidate.isNotEmpty(parentId)) {
					map.put("parentId_dictText", getParentDepartmentName(delegator, parentId));
				    }
		    }
		    map.putAll(person);
		    result.add(map);
		}
    	} catch (Exception e) {
    	    Debug.logError(e.getMessage(), module);
    	}
   
       return result;
    	
    	
    }
    
    private static List buildPersonList(Delegator delegator,List<GenericValue> inList){
    	List result=new ArrayList();
    	try {
    	for(GenericValue hrResign:inList) {
    		Map map =new HashMap();
    	
    			
    		map.putAll(hrResign);
    		String partyId =hrResign.getString("partyId");
    		GenericValue person =delegator.findOne("Person", true, UtilMisc.toMap("partyId", partyId));
    		map.putAll(person);
		    String departmentId = person.getString("departmentId");
		    String partyId_dictText = person.getString("name");
		    map.put("partyId_dictText", partyId_dictText);
		    List<GenericValue> hrDepartmentInfo = delegator.findByAnd("HrDepartment",
			    UtilMisc.toMap("departmentId", departmentId), UtilMisc.toList("id"), true);
		    GenericValue hrDepartment = EntityUtil.getFirst(hrDepartmentInfo);
		    if (UtilValidate.isNotEmpty(hrDepartment)) {
			String departmentId_dictText = hrDepartment.getString("name");
			map.put("departmentId_dictText", departmentId_dictText);
			String parentId = hrDepartment.getString("parentId");
				if (UtilValidate.isNotEmpty(parentId)) {
					map.put("parentId_dictText", getParentDepartmentName(delegator, parentId));
				    }
		    }
		    map.putAll(person);
		    result.add(map);
		}
    	} catch (Exception e) {
    	    Debug.logError(e.getMessage(), module);
    	}
   
       return result;
    	
    	
    }
    
    private static String getParentDepartmentName(Delegator delegator,String departmentId) throws GenericEntityException{
    	String departmentId_dictText="";
    	List<GenericValue> hrDepartmentInfo = delegator.findByAnd("HrDepartment",
			    UtilMisc.toMap("departmentId", departmentId), UtilMisc.toList("id"), true);
		    GenericValue hrDepartment = EntityUtil.getFirst(hrDepartmentInfo);
		    if (UtilValidate.isNotEmpty(hrDepartment)) {
			   departmentId_dictText = hrDepartment.getString("name");
			
		    }
		    return departmentId_dictText;
    }
    
    
    

    /**
     * 根据入职记录生成员工
     */

    public static Map<String, Object> createHrEmployeeFromEntryRecord(DispatchContext ctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = ctx.getDelegator();
	String id = (String) context.get("id");
	try {

	    GenericValue gvHrEmployeeEntryRecord = delegator.findOne("HrEmployeeRecord", UtilMisc.toMap("id", id),
		    false);
	    String partyId = IDGenerator.getId();
	    GenericValue party = delegator.makeValue("Party", UtilMisc.toMap("partyId", partyId));
	    party.set("partyTypeId", "PERSON");
	    GenericValue partyRole = delegator.makeValue("PartyRole", UtilMisc.toMap("partyId", partyId));
	    partyRole.set("roleTypeId", "EMPLOYEE");
	    delegator.create(party);
	    delegator.create(partyRole);

	    GenericValue person = delegator.makeValue("Person", UtilMisc.toMap("partyId", partyId));
	    person.setNonPKFields(gvHrEmployeeEntryRecord);
	    person.set("typeId", "EMPLOYEE");
	    person.set("legalStatusId", "LEGAL_APPLY");
	    person.set("sourceId", id);
	    person.set("isModule", "HR");
	    delegator.create(person);

	    gvHrEmployeeEntryRecord.set("entryType", "Y");

	    delegator.store(gvHrEmployeeEntryRecord);

	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    public static Map<String, Object> uniquePersonWxUserId(DispatchContext ctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = ctx.getDelegator();
	String uniqueWxUserId = "Y";
	String wxUserId = (String) context.get("wxUserId");
	try {

	    List<GenericValue> gvHrEmployeeInfo = delegator.findByAnd("Person", UtilMisc.toMap("wxUserId", wxUserId),
		    null, false);

	    if (UtilValidate.isNotEmpty(gvHrEmployeeInfo)) {
		uniqueWxUserId = "N";
	    }

	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	result.put("uniqueWxUserId", uniqueWxUserId);
	return result;
    }

    public static Map<String, Object> addPersonCompanyEmail(DispatchContext ctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = ctx.getDelegator();
	try {

	    List<GenericValue> gvHrEmployeeList = delegator.findByAnd("Person", UtilMisc.toMap("typeId", "EMPLOYEE"),
		    null, false);

	    for (GenericValue gvHrEmployee : gvHrEmployeeList) {

		if (UtilValidate.isNotEmpty(gvHrEmployee.getString("wxUserId"))
			&& UtilValidate.isEmpty(gvHrEmployee.getString("companyEmail"))) {
		    String wxUserId = gvHrEmployee.getString("wxUserId");
		    if (wxUserId.endsWith("@kejicloud.com")) {
			GenericValue person = delegator.findOne("Person",
				UtilMisc.toMap("partyId", gvHrEmployee.getString("partyId")), false);
			person.set("companyEmail", wxUserId);
			delegator.store(person);
		    }

		}
	    }

	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }
//
//    // 按BU 统计每月离职人数、入职人数、月初在职人员、月末在职人员（离职率、入职率）
//    @SuppressWarnings({ "rawtypes", "unchecked" })
//    public static Map<String, Object> reportEmployeeRecordResign(DispatchContext ctx,
//	    Map<String, ? extends Object> context) {
//	Map<String, Object> result = ServiceUtil.returnSuccess();
//	Delegator delegator = ctx.getDelegator();
//
//	List columns = UtilMisc.toList("序号", "BU", "月份", "离职人数", "入职人数", "月初在职人员", "月末在职人员", "离职率", "入职率");
//	List records = new ArrayList();
//	try {
////    		String setYear = (String) context.get("setParam1");//2021-04
////    		String setMonth = (String) context.get("setParam2");//2021-04
//
//	    List<GenericValue> gvHrEmployeeList = delegator.findByAnd("Person", UtilMisc.toMap("typeId", "EMPLOYEE"),
//		    null, false);
//
//	    List<GenericValue> gvHrDepartmentList = delegator.findByAnd("HrDepartment", UtilMisc.toMap("parentId", "1"),
//		    null, false);
//	    for (GenericValue gvHrDepartment : gvHrDepartmentList) {
//		String departmentName = gvHrDepartment.getString("name");
//		String departmentId = gvHrDepartment.getString("departmentId");
//		String thisMonth = getThisMonth();
//		int resignPersonNumber = resignPersonNumber(gvHrEmployeeList, departmentId, thisMonth);
//		int recordPersonNumber = recordPersonNumber(gvHrEmployeeList, departmentId, thisMonth);
//		int prePersonNumber = prePersonNumber(gvHrEmployeeList, departmentId, thisMonth);
//		int thisPersonNumber = thisPersonNumber(gvHrEmployeeList, departmentId, thisMonth);
//
//		DecimalFormat df = new DecimalFormat("0.00");
//		if (thisPersonNumber == 0) {
//		    thisPersonNumber = 1;
//		}
//		String resignRate = df.format((float) resignPersonNumber / thisPersonNumber);
//		String recordRate = df.format((float) recordPersonNumber / thisPersonNumber);
//		Map record = new HashMap();
//		record.put("departmentName", departmentName);
//		record.put("thisMonth", thisMonth);
//		record.put("resignPersonNumber", resignPersonNumber);
//		record.put("recordPersonNumber", recordPersonNumber);
//		record.put("prePersonNumber", prePersonNumber);
//		record.put("thisPersonNumber", thisPersonNumber);
//		record.put("resignRate", resignRate + "%");
//		record.put("recordRate", recordRate + "%");
//
//		records.add(record);
//	    }
//	    result.put("records", records);// 记录
//	    result.put("columns", columns);// 列名
//
//	} catch (GenericEntityException e) {
//	    Debug.logError(e.getMessage(), module);
//	}
//	return result;
//    }
    
    
//    // 按BU 统计每月离职人数、入职人数、月初在职人员、月末在职人员（离职率、入职率）
//    @SuppressWarnings({ "rawtypes", "unchecked" })
//    public static Map<String, Object> getEmployeeRecordResignReport(DispatchContext ctx,
//	    Map<String, ? extends Object> context) {
//	Map<String, Object> result = ServiceUtil.returnSuccess();
//	Delegator delegator = ctx.getDelegator();
//
//	List columns = UtilMisc.toList("序号", "BU", "月份", "离职人数", "入职人数", "月初在职人员", "月末在职人员", "离职率", "入职率");
//	List records = new ArrayList();
//	try {
//    		String setYearMonth = (String) context.get("setYearMonth");//2021-04
//
//    		if(!setYearMonth.contains("-")) {
//    			return result;
//    		}
//    		String[]	setYearMonthArray	=setYearMonth.split("-");
//    	int year= Integer.valueOf(setYearMonthArray[0]);
//    	int month= Integer.valueOf(setYearMonthArray[1]);
//    		Timestamp fromDate =getFirstDayOfMonth(year, month);// 2021-04
//    	    Timestamp thruDate =getLastDayOfMonth(year, month);// 2021-04
//    	   
//    		
//    	    
//    	    List mainCond1 = new ArrayList();
//    	    mainCond1.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
//    	    // 部门列表
//    	    List<GenericValue> gvHrDepartmentList = delegator.findByAnd("HrDepartment", UtilMisc.toMap("parentId", "1"),
//    		    null, false);
//
//    	    Long resignPersonNumberAll = 0L;
//    	    Long buNumAll = 0L;
//    	    Long recordPersonNumberAll = 0L;
//    	    Long prePersonNumberAll = 0L;
//    	    DecimalFormat df = new DecimalFormat("0.00");
//
//    	    for (GenericValue gvHrDepartment : gvHrDepartmentList) {
//    		String departmentName = gvHrDepartment.getString("name");
//    		String departmentId = gvHrDepartment.getString("departmentId");
//
//    		// 部门离职人数
//    		List mainCond2 = new ArrayList();
//    		if (UtilValidate.isNotEmpty(fromDate)) {
//    		    mainCond2.add(EntityCondition.makeCondition("notWorkDate", EntityOperator.GREATER_THAN_EQUAL_TO,
//    			    fromDate));
//    		}
//    		if (UtilValidate.isNotEmpty(thruDate)) {
//    		    mainCond2.add(EntityCondition.makeCondition("notWorkDate", EntityOperator.LESS_THAN, thruDate));
//    		}
//    		mainCond2.add(EntityCondition.makeCondition("workState", EntityOperator.EQUALS, "2"));
//    		mainCond2.add(EntityCondition.makeCondition("departmentId", EntityOperator.EQUALS, departmentId));
//    		mainCond2.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
//    		Long resignPersonNumber = delegator.findCountByCondition("Person",
//    			EntityCondition.makeCondition(mainCond2, EntityOperator.AND), null, null);
//    		resignPersonNumberAll = resignPersonNumberAll + resignPersonNumber;
//    		
//    		
//    		
//    		// 部门入职人数
//    		List mainCondRecordPersonNumber = new ArrayList();
//    		if (UtilValidate.isNotEmpty(fromDate)) {
//    		    mainCondRecordPersonNumber.add(EntityCondition.makeCondition("beginDate", EntityOperator.GREATER_THAN_EQUAL_TO,
//    			    fromDate));
//    		}
//    		if (UtilValidate.isNotEmpty(thruDate)) {
//    		    mainCondRecordPersonNumber.add(EntityCondition.makeCondition("beginDate", EntityOperator.LESS_THAN, thruDate));
//    		}
//    		//mainCondRecordPersonNumber.add(EntityCondition.makeCondition("workState", EntityOperator.EQUALS, "2"));
//    		mainCondRecordPersonNumber.add(EntityCondition.makeCondition("departmentId", EntityOperator.EQUALS, departmentId));
//    		mainCondRecordPersonNumber.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
//    		Long recordPersonNumber = delegator.findCountByCondition("Person",
//    			EntityCondition.makeCondition(mainCondRecordPersonNumber, EntityOperator.AND), null, null);
//    		recordPersonNumberAll = recordPersonNumberAll + recordPersonNumber;
//    		
//    		
//    		//1月  10 +1  -2  
//    		//2月  9  +2  -1   10
//    		
//    		// 部门在职人数
//    		List mainCond3 = new ArrayList();
//    		mainCond3.add(EntityCondition.makeCondition("departmentId", EntityOperator.EQUALS, departmentId));
//    		mainCond3.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
//    		mainCond3.add(EntityCondition.makeCondition("workState", EntityOperator.NOT_EQUAL, "2"));
//    		Long buNum = delegator.findCountByCondition("Person",
//    			EntityCondition.makeCondition(mainCond3, EntityOperator.AND), null, null);
//
//    		buNumAll = buNumAll + buNum;
//    		
//    		//月初
//    		long prePersonNumber =buNum -recordPersonNumber+resignPersonNumber;
//    		prePersonNumberAll = prePersonNumberAll + prePersonNumber;
//
//    		String resignRate = "";
//    		if (buNum == 0) {
//    		    resignRate = "0";
//    		} else {
//    		    resignRate = df.format((float)resignPersonNumber /(buNum+resignPersonNumber) * 100);
//    		}
//    		
//    		String recordRate = "";
//    		if (buNum == 0) {
//    			recordRate = "0";
//    		} else {
//    			recordRate = df.format((float)recordPersonNumber / buNum * 100);
//    		}
//    		
//    		Map record = new HashMap();
//    		record.put("departmentId", departmentId);
//    		record.put("departmentName", departmentName);
//    		
//    		record.put("thisMonth", setYearMonth);
//    		record.put("resignPersonNumber", resignPersonNumber);
//    		record.put("recordPersonNumber", recordPersonNumber);
//    		record.put("prePersonNumber", prePersonNumber);
//    		record.put("thisPersonNumber", buNum);
//    		record.put("resignRate", resignRate + "%");
//    		record.put("recordRate", recordRate + "%");
//
//
//    		records.add(record);
//    	    }
//    	    // 汇总
//    	    String resignRateAll = "";
//    	    if (buNumAll == 0) {
//    	    	resignRateAll = "0";
//    	    } else {
//    	    	resignRateAll = df.format((float)resignPersonNumberAll / (buNumAll+resignPersonNumberAll) * 100);
//    	    }
//    	    
//    	    String recordRateAll = "";
//    		if (buNumAll == 0) {
//    			recordRateAll = "0";
//    		} else {
//    			recordRateAll = df.format((float)recordPersonNumberAll / buNumAll * 100);
//    		}
//    	    Map record = new HashMap();
//    	   
//            record.put("departmentName", "汇总");
//    		
//    		record.put("thisMonth", setYearMonth);
//    		record.put("resignPersonNumber", resignPersonNumberAll);
//    		record.put("recordPersonNumber", recordPersonNumberAll);
//    		record.put("prePersonNumber", prePersonNumberAll);
//    		record.put("thisPersonNumber", buNumAll);
//    		record.put("resignRate", resignRateAll + "%");
//    		record.put("recordRate", recordRateAll + "%");
//    	    records.add(record);
//
//    	    
//    	    
//
//    	    Map<String, Object> nfs = FastMap.newInstance();
//    	    nfs.put("records", records);
//    	    nfs.put("columns", columns);// 列名
//    	    result.put("nfs", nfs);// 记录
//	   
//	
//	} catch (GenericEntityException e) {
//	    Debug.logError(e.getMessage(), module);
//	}
//	return result;
//    }
//    
//    
    
    
    /**
     * 获取指定年月的第一天
     * @param year
     * @param month
     * @return
     */
    public static Timestamp getFirstDayOfMonth(int year, int month) {     
        Calendar cal = Calendar.getInstance();   
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份 
        cal.set(Calendar.MONTH, month-1); 
        //获取某月最小天数
        int firstDay = cal.getMinimum(Calendar.DATE);
        //设置日历中月份的最小天数 
        cal.set(Calendar.DAY_OF_MONTH,firstDay);  
         
        Timestamp returnTime = new Timestamp(cal.getTime().getTime());
        return returnTime;  
    }
    
    /**
     * 获取指定年月的最后一天
     * @param year
     * @param month
     * @return
     */
     public static Timestamp getLastDayOfMonth(int year, int month) {     
         Calendar cal = Calendar.getInstance();     
         //设置年份  
         cal.set(Calendar.YEAR, year);  
         //设置月份  
         cal.set(Calendar.MONTH, month-1); 
         //获取某月最大天数
         int lastDay = cal.getActualMaximum(Calendar.DATE);
         //设置日历中月份的最大天数  
         cal.set(Calendar.DAY_OF_MONTH, lastDay);  
         Timestamp returnTime = new Timestamp(cal.getTime().getTime());
         return returnTime;  
     }
    /**
     * 获取指定年月的第一天
     * @param year
     * @param month
     * @return
     */
    public static String getFirstDayOfMonth1(int year, int month) {     
        Calendar cal = Calendar.getInstance();   
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份 
        cal.set(Calendar.MONTH, month-1); 
        //获取某月最小天数
        int firstDay = cal.getMinimum(Calendar.DATE);
        //设置日历中月份的最小天数 
        cal.set(Calendar.DAY_OF_MONTH,firstDay);  
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());  
    }
    
    /**
     * 获取指定年月的最后一天
     * @param year
     * @param month
     * @return
     */
     public static String getLastDayOfMonth1(int year, int month) {     
         Calendar cal = Calendar.getInstance();     
         //设置年份  
         cal.set(Calendar.YEAR, year);  
         //设置月份  
         cal.set(Calendar.MONTH, month-1); 
         //获取某月最大天数
         int lastDay = cal.getActualMaximum(Calendar.DATE);
         //设置日历中月份的最大天数  
         cal.set(Calendar.DAY_OF_MONTH, lastDay);  
         //格式化日期
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
         return sdf.format(cal.getTime());
     }
    

//  //按BU 统计每月离职人数、入职人数、月初在职人员、月末在职人员（离职率、入职率）
//    public static Map<String, Object> reportEmployeeRecordResign_old(DispatchContext ctx,
//    	    Map<String, ? extends Object> context) {
//    	Map<String, Object> result = ServiceUtil.returnSuccess();
//    	Delegator delegator = ctx.getDelegator();
//    	LocalDispatcher dispatcher = ctx.getDispatcher();
//    	
//    	List columns = UtilMisc.toList("序号","BU","月份","离职人数","入职人数","月初在职人员","月末在职人员","离职率","入职率");
//    	List records = new ArrayList();
//    	try {
////    		String setYear = (String) context.get("setParam1");//2021-04
////    		String setMonth = (String) context.get("setParam2");//2021-04
//    		
//    	    List<GenericValue> gvHrEmployeeList = delegator.findByAnd("Person", UtilMisc.toMap("typeId", "EMPLOYEE"),null, false);
//    	    
//    	    
//    	    List<GenericValue> gvHrDepartmentList = delegator.findByAnd("HrDepartment", UtilMisc.toMap("parentId", "1"),null, false);
////    	    for(int i=0;i<=gvHrDepartmentList.size();i++) {
//    	    for(GenericValue gvHrDepartment:gvHrDepartmentList) {
//    	    //	GenericValue gvHrDepartment=gvHrDepartmentList.get(i);
//    	    	String departmentName =gvHrDepartment.getString("name");
//    	    	String departmentId =gvHrDepartment.getString("departmentId");
//    	    	String thisMonth =getThisMonth();
//    	    	int resignPersonNumber=resignPersonNumber(gvHrEmployeeList, departmentId, thisMonth);
//    	    	int recordPersonNumber=recordPersonNumber(gvHrEmployeeList, departmentId, thisMonth);
//    	    	int prePersonNumber=prePersonNumber(gvHrEmployeeList, departmentId, thisMonth);
//    	    	int thisPersonNumber=thisPersonNumber(gvHrEmployeeList, departmentId, thisMonth);
//    	    	
//    	    	DecimalFormat df=new DecimalFormat("0.00");
//    	   	    String resignRate=df.format((float)resignPersonNumber/thisPersonNumber);
//    	   	    String recordRate=df.format((float)recordPersonNumber/thisPersonNumber);
//    	    	List record = new ArrayList();
//    	    	//record.add(i);
//    	    	record.add(departmentName);
//    	    	record.add(thisMonth);
//    	    	record.add(resignPersonNumber);
//    	    	record.add(recordPersonNumber);
//    	    	record.add(prePersonNumber);
//    	    	record.add(thisPersonNumber);
//    	    	record.add(resignRate+"%");
//    	    	record.add(recordRate+"%");
//    	    	
//    	    	
//    	    	records.add(record);
//    	    }
//    		result.put("records", records);// 记录
//    		result.put("columns", columns);// 列名
//    		
//    	    
//    	} catch (GenericEntityException e) {
//    	    Debug.logError(e.getMessage(), module);
//    	}
//    	return result;
//        }
//    // 离职人数
//    private static int resignPersonNumber(List<GenericValue> gvHrEmployeeList, String thisDepartmentId,
//	    String thisMonth) {
//	int result = 0;
//	for (GenericValue gvHrEmployee : gvHrEmployeeList) {
//	    Timestamp notWorkDate = gvHrEmployee.getTimestamp("notWorkDate");
//	    String departmentId = gvHrEmployee.getString("departmentId");
//	    if (UtilValidate.isNotEmpty(notWorkDate)) {
//		if (thisMonth.equals(getMonth(notWorkDate)) && thisDepartmentId.equals(departmentId)) {
//		    result = result + 1;
//		}
//	    }
//
//	}
//	return result;
//    }
//    // 入职人数
//
//    private static int recordPersonNumber(List<GenericValue> gvHrEmployeeList, String thisDepartmentId,
//	    String thisMonth) {
//	int result = 0;
//	for (GenericValue gvHrEmployee : gvHrEmployeeList) {
//	    Timestamp beginDate = gvHrEmployee.getTimestamp("beginDate");
//	    String departmentId = gvHrEmployee.getString("departmentId");
//	    if (UtilValidate.isNotEmpty(beginDate)) {
//		if (thisMonth.equals(getMonth(beginDate)) && thisDepartmentId.equals(departmentId)) {
//		    result = result + 1;
//		}
//	    }
//
//	}
//	return result;
//    }
//
//    // 月初在职人员
//    private static int prePersonNumber(List<GenericValue> gvHrEmployeeList, String thisDepartmentId, String thisMonth) {
//	int result = 0;
//	for (GenericValue gvHrEmployee : gvHrEmployeeList) {
//	    Timestamp notWorkDate = gvHrEmployee.getTimestamp("notWorkDate");
//	    String departmentId = gvHrEmployee.getString("departmentId");
//	    if (UtilValidate.isEmpty(notWorkDate) && thisDepartmentId.equals(departmentId)) {
//		result = result + 1;
//	    }
//	    if (UtilValidate.isNotEmpty(notWorkDate)) {
//		if (thisMonth.equals(getMonth(notWorkDate)) && thisDepartmentId.equals(departmentId)) {
//		    result = result + 1;
//		}
//	    }
//
//	}
//	return result;
//    }
//
//    // 月末在职人员
//    private static int thisPersonNumber(List<GenericValue> gvHrEmployeeList, String thisDepartmentId,
//	    String thisMonth) {
//	int result = 0;
//	for (GenericValue gvHrEmployee : gvHrEmployeeList) {
//	    Timestamp notWorkDate = gvHrEmployee.getTimestamp("notWorkDate");
//	    String departmentId = gvHrEmployee.getString("departmentId");
//	    if (UtilValidate.isEmpty(notWorkDate) && thisDepartmentId.equals(departmentId)) {
//		result = result + 1;
//	    }
//	}
//	return result;
//    }

//   时间段选取，按报表展示：
//   部门、职级、员工类型、管培生
//   1、表格形式：
//     1.1、BU1，离职人数，在职人数，离职率（离职人员数量➗全体人员数量，含离职人员）；
//     1.2、BU2，离职人数，在职人数，离职率（离职人员数量➗全体人员数量，含离职人员）；
//     1.3、。。。
//     1.4、汇总
//   2、点击BU钻取展开，按照离职原因group by；
//    // 离职原因选项：工作文化、家庭原因、身体原因、薪酬福利、职业发展、管理因素
//
//    @SuppressWarnings({ "rawtypes", "unchecked" })
//    public static Map<String, Object> getResignReport(DispatchContext ctx, Map<String, ? extends Object> context) {
//	Map<String, Object> result = ServiceUtil.returnSuccess();
//	Delegator delegator = ctx.getDelegator();
////	List columns = UtilMisc.toList("BU", "离职人数", "在职人数", "离职率");
//	List records = new ArrayList();
//	try {
//	    Timestamp fromDate = (Timestamp) context.get("fromDate");// 2021-04
//	    Timestamp thruDate = (Timestamp) context.get("thruDate");// 2021-04
//	   // String buId = (String) context.get("departmentId");
//	    List mainCond1 = new ArrayList();
//	    mainCond1.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
//	    // 部门列表
//	    List<GenericValue> gvHrDepartmentList = delegator.findByAnd("HrDepartment", UtilMisc.toMap("parentId", "1"),
//		    null, false);
//
//	    Long quitNumAll = 0L;
//	    Long buNumAll = 0L;
////	    Long onlineNumAll = 0L;
//	    DecimalFormat df = new DecimalFormat("0.00");
//
//	    for (GenericValue gvHrDepartment : gvHrDepartmentList) {
//		String departmentName = gvHrDepartment.getString("name");
//		String departmentId = gvHrDepartment.getString("departmentId");
//
//		// 部门离职人数
//		List mainCond2 = new ArrayList();
//		if (UtilValidate.isNotEmpty(fromDate)) {
//		    mainCond2.add(EntityCondition.makeCondition("notWorkDate", EntityOperator.GREATER_THAN_EQUAL_TO,
//			    fromDate));
//		}
//		if (UtilValidate.isNotEmpty(thruDate)) {
//		    mainCond2.add(EntityCondition.makeCondition("notWorkDate", EntityOperator.LESS_THAN, thruDate));
//		}
//		mainCond2.add(EntityCondition.makeCondition("workState", EntityOperator.EQUALS, "2"));
//		mainCond2.add(EntityCondition.makeCondition("departmentId", EntityOperator.EQUALS, departmentId));
//		mainCond2.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
//		Long quitNum = delegator.findCountByCondition("Person",
//			EntityCondition.makeCondition(mainCond2, EntityOperator.AND), null, null);
//		quitNumAll = quitNumAll + quitNum;
//		// 部门所有在线人数
//		List mainCond3 = new ArrayList();
//		mainCond3.add(EntityCondition.makeCondition("departmentId", EntityOperator.EQUALS, departmentId));
//		mainCond3.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
//		mainCond2.add(EntityCondition.makeCondition("workState", EntityOperator.NOT_EQUAL, "2"));
//		Long buNum = delegator.findCountByCondition("Person",
//			EntityCondition.makeCondition(mainCond3, EntityOperator.AND), null, null);
//
//		buNumAll = buNumAll + buNum;
////		// 部门在职人数
////		Long onlineNum = buNum - quitNum;
////		onlineNumAll = onlineNumAll + onlineNum;
//
//		String resignRate = "";
//		if (buNum == 0) {
//		    resignRate = "0";
//		} else {
//		    resignRate = df.format((float)quitNum / (buNum+quitNum) * 100);
//		}
//		
//		Map record = new HashMap();
//		record.put("departmentId", departmentId);
//		record.put("departmentName", departmentName);
//		record.put("quitNum", quitNum);
//		record.put("onlineNum", buNum);
//		record.put("resignRate", resignRate + "%");
//
//		records.add(record);
//	    }
//	    // 汇总
//	    String resignRate = "";
//	    if (buNumAll == 0) {
//		resignRate = "0";
//	    } else {
//		resignRate = df.format((float)quitNumAll / (buNumAll+quitNumAll) * 100);
//	    }
//	    Map record = new HashMap();
//	    record.put("departmentName", "汇总");
//	    record.put("quitNum", quitNumAll);
//	    record.put("onlineNum", buNumAll);
//	    record.put("resignRate", resignRate + "%");
//	    records.add(record);
//
//	    
//	    
//
//	    Map<String, Object> nfs = FastMap.newInstance();
//	    nfs.put("records", records);
//	 //   nfs.put("buRecords", buRecords);
//
//	    result.put("nfs", nfs);// 记录
//	} catch (GenericEntityException e) {
//	    Debug.logError(e.getMessage(), module);
//	}
//	return result;
//    }
//    
//    
//    
//    public static Map<String, Object> getResignReportByBuId(DispatchContext ctx, Map<String, ? extends Object> context) {
//    	Map<String, Object> result = ServiceUtil.returnSuccess();
//    	Delegator delegator = ctx.getDelegator();
//    	//List records = new ArrayList();
//    	try {
//    	    Timestamp fromDate = (Timestamp) context.get("fromDate");// 2021-04
//    	    Timestamp thruDate = (Timestamp) context.get("thruDate");// 2021-04
//    	    String buId = (String) context.get("departmentId");
//    	    
//    	    
//    	    List buRecords = new ArrayList();
//    	    if (UtilValidate.isNotEmpty(buId)) {
//    		List<GenericValue> stateList = delegator.findByAnd("DataDictionary",
//    			UtilMisc.toMap("dictionaryTypeId", "RESIGN_REASON"), UtilMisc.toList("sequenceId"), false);
//
//    		for (GenericValue state : stateList) {
//    		    String code = state.getString("dictionaryCode");
//    		    String desc = state.getString("description");
//    		    // 部门离职人数
//    		    List mainCond2 = new ArrayList();
//    		    if (UtilValidate.isNotEmpty(fromDate)) {
//    			mainCond2.add(EntityCondition.makeCondition("resignDate", EntityOperator.GREATER_THAN_EQUAL_TO,
//    				fromDate));
//    		    }
//    		    if (UtilValidate.isNotEmpty(thruDate)) {
//    			mainCond2.add(EntityCondition.makeCondition("resignDate", EntityOperator.LESS_THAN, thruDate));
//    		    }
//    		    if (!"all".equals(buId)) {
//    		       mainCond2.add(EntityCondition.makeCondition("buId", EntityOperator.EQUALS, buId));
//    		    }
//    		    mainCond2.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "2"));
//
//    		    mainCond2.add(EntityCondition.makeCondition("content", EntityOperator.EQUALS, code));
//
//    		    Long quitNum = delegator.findCountByCondition("HrResign",
//    			    EntityCondition.makeCondition(mainCond2, EntityOperator.AND), null, null);
//
//    		    buRecords.add(UtilMisc.toMap("name", desc, "quitNum", quitNum));
//    		}
//    	    }
//    	    Map<String, Object> nfs = FastMap.newInstance();
//    	//    nfs.put("records", records);
//    	    nfs.put("buRecords", buRecords);
//
//    	    result.put("nfs", nfs);// 记录 
//    	    
//    	} catch (GenericEntityException e) {
//    	    Debug.logError(e.getMessage(), module);
//    	}
//    	return result;
//        }
//
//    private static String getMonth(Timestamp timestamp) {
//	Calendar c = Calendar.getInstance(); // 这句好像很浪费，我也不知道该怎么处理
//	c.setTime(timestamp);// 将Date或Timestamp放进去
//	System.out.println(c.get(Calendar.YEAR)); // 取出年份
//	System.out.println(c.get(Calendar.MONTH) + 1); // 取出月份，要加1，因为是从0开始的(!)不知道为什么Sun要这样?
//	System.out.println(c.get(Calendar.DATE)); // 取出日期
//	return c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + 1;
//    }

    // 得到上个月份
    protected static String getPreMonth() {
	LocalDate today = LocalDate.now();
	today = today.minusMonths(1);
	DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM");
	return formatters.format(today);
    }

    // 得到本月的月份
    protected static String getThisMonth() {
	LocalDate today = LocalDate.now();
	// today = today.minusMonths(1);
	DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM");
	return formatters.format(today);
    }

//    public static void main1(String[] args) {
////    	String ss=getThisMonth();
////        System.out.println(ss);
////        Calendar c = Calendar.getInstance(); //这句好像很浪费，我也不知道该怎么处理
//// 	   //c.setTime(timestamp);//将Date或Timestamp放进去
//// 	   System.out.println(c.get(Calendar.YEAR));    //取出年份
//// 	   System.out.println(c.get(Calendar.MONTH)+1); //取出月份，要加1，因为是从0开始的(!)不知道为什么Sun要这样?
//// 	   System.out.println(c.get(Calendar.DATE));    //取出日期
//
//	int resignPersonNumber = 4;
//	int thisPersonNumber = 50;
//	DecimalFormat df = new DecimalFormat("0.00");
//	String resignRate = df.format((float) resignPersonNumber / thisPersonNumber);
//	System.out.println(resignRate);
//
//    }
//
//
//    public static void main2(String[] args) {
//	// String date = "2008-06-12";
////	Date date = new Date(2014 - 1900, 6 - 1, 12);
////	Date nowDate = UtilDateTime.nowDate();
////	Long ss = yearCompare(date, nowDate);
////	System.out.println(ss);
//    	String ids="1;2;3;4";
//    	System.out.print(toSqlInParam(ids));
//    }
    
    private static String toSqlInParam(String ids){
    	String result="";
    
    	String[] idsArray =ids.split(";");
    	for(int i=0;i<idsArray.length;i++) {
    		String id=idsArray[i];
    		if(i>0) {result=result+",";}
    		result=result+"'"+id+"'";
    	}
    	return result;
    	
    }
    

    /**
     * 根据入职日期生成工龄
     */

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map<String, Object> generateBeginDateYearNumEmployeeByBeginDate(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();
	try {
	    List toBeStore = new ArrayList();
	    List<GenericValue> personList = delegator.findByAnd("Person", UtilMisc.toMap("typeId", "EMPLOYEE"), null,
		    true);
	    Debug.log("personList ===" + personList);
	    Date nowDate = UtilDateTime.nowDate();
	    for (GenericValue person : personList) {

		Timestamp beginDate = person.getTimestamp("beginDate");
		String partyId = person.getString("partyId");
		if (UtilValidate.isNotEmpty(beginDate)) {
		    Long beginDateYearNum = yearCompare(beginDate, nowDate);
		    GenericValue entity = delegator.findOne("Person", false, UtilMisc.toMap("partyId", partyId));
		    entity.set("beginDateYearNum", beginDateYearNum);
		    toBeStore.add(entity);
		}

	    }
	    delegator.storeAll(toBeStore);

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	return result;
    }

    /**
     * 根据入职日期生成工龄
     */

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map<String, Object> generateAgeEmployeeByBirthday(DispatchContext dctx,
	    Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();

	Map<String, Object> result = new HashMap<>();
	try {

	    List toBeStore = new ArrayList();

	    List<GenericValue> personList = delegator.findByAnd("Person", UtilMisc.toMap("typeId", "EMPLOYEE"), null,
		    true);
	    Debug.log("personList ===" + personList);
	    Date nowDate = UtilDateTime.nowDate();
	    for (GenericValue person : personList) {

		Timestamp birthday = person.getTimestamp("birthday");
		String partyId = person.getString("partyId");
		if (UtilValidate.isNotEmpty(birthday)) {
		    Long age = yearCompare(birthday, nowDate);
		    GenericValue entity = delegator.findOne("Person", false, UtilMisc.toMap("partyId", partyId));
		    entity.set("age", age);
		    toBeStore.add(entity);
		}

	    }
	    delegator.storeAll(toBeStore);

	} catch (Exception e) {
	    Debug.log(e.getMessage());
	}

	return result;
    }

    /**
     * 计算2个日期之间相差多少年
     */
    public static Long yearCompare(Date fromDate, Date toDate) {
	Calendar from = Calendar.getInstance();
	from.setTime(fromDate);
	Calendar to = Calendar.getInstance();
	to.setTime(toDate);
	// 只要年
	int fromYear = from.get(Calendar.YEAR);
	int toYear = to.get(Calendar.YEAR);
	Integer year = toYear - fromYear;
	return year.longValue();
    }
    
    public static void main(String[] args) throws Exception {
    	//String birthday ="1999-01-05 00:00:00";
    	String birthday ="1998-11-07";
    	
//    	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//    	Calendar cal = Calendar.getInstance();
//    	int yearNow = cal.get(Calendar.YEAR);// 年
//    	cal.setTime(formatter.parse(birthday));
//    	int birthyear=cal.get(Calendar.YEAR);
//    	while(birthyear<yearNow){
//    	cal.set(Calendar.YEAR,cal.get(Calendar.YEAR)+1);
//    	birthyear=cal.get(Calendar.YEAR);
//    	}
//    	Date ed=new Date();
//    	Date sd=cal.getTime();
//    	long days=0;
//    	if((ed.getTime() - sd.getTime()) / (3600 * 24 * 1000)> 0 ){
//    	days=(ed.getTime() - sd.getTime()) / (3600 * 24 * 1000);
//    	System.out.println("距离你生日还有" + days + "天");
//    	}else{
//    	cal.set(Calendar.YEAR,cal.get(Calendar.YEAR)+1);
//    	sd=cal.getTime();
//    	days=(ed.getTime() - sd.getTime()) / (3600 * 24 * 1000);
//    	System.out.println("距离你生日还有" + days + "天");
//    	}
    	
    	long ii =getBirthDayNumber( birthday);
    	System.out.println("距离你生日还有" + ii + "天");
    	}
    
    
    public static long getBirthDayNumber(String birthday) throws ParseException{
    	
    	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    	Calendar cal = Calendar.getInstance();
    	int yearNow = cal.get(Calendar.YEAR);// 年
    	cal.setTime(formatter.parse(birthday));
    	int birthyear=cal.get(Calendar.YEAR);
    	while((birthyear)<yearNow){
    	cal.set(Calendar.YEAR,cal.get(Calendar.YEAR)+1);
    	birthyear=cal.get(Calendar.YEAR);
    	}
    	//System.out.println("yearNow = " +yearNow);
    	//System.out.println("birthyear = " +birthyear);
    	Date ed=new Date();
    	Date sd=cal.getTime();
    	long days=0;
    	//System.out.println("ed.getTime() = " +ed.getTime());
    	//System.out.println("sd.getTime() = " +sd.getTime());
    	//Debug.log("== "+(ed.getTime() - sd.getTime()) / (3600 * 24 * 1000));
    	if((ed.getTime() - sd.getTime()) / (3600 * 24 * 1000)> 0 ){
    		cal.set(Calendar.YEAR,cal.get(Calendar.YEAR)+1);
    		sd=cal.getTime();
    	days=(sd.getTime() - ed.getTime()) / (3600 * 24 * 1000);
    	//System.out.println("1距离你生日还有" + days + "天");
    	}else{
    	//cal.set(Calendar.YEAR,cal.get(Calendar.YEAR)+1);
    	
    	days=(sd.getTime() - ed.getTime()) / (3600 * 24 * 1000);
    	//System.out.println("2距离你生日还有" + days + "天");
    	}
    	Debug.log(birthday);
    	Debug.log("距离你生日还有" + days + "天");
    return days;
    
    }
    

    
 
}
